<template>
  <div class="roleSet">
    <div class="content__body">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" class="width-custom"></el-input>
        </el-form-item>
        <el-form-item label="角色区分" prop="roleMark">
          <el-select
            v-model="formData.roleMark"
            placeholder="请选择"
            :disabled="props.mode === 'edit'"
          >
            <el-option
              v-for="item in innerRoleList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="formData.roleType" placeholder="请选择">
            <el-option
              v-for="item in roleTypeEnum"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="formData.roleDesc" class="width-custom"></el-input>
        </el-form-item>
      </el-form>
      <div class="content__body__tree">
        <p>菜单分配</p>
        <el-skeleton
          style="height: 10vh"
          :rows="4"
          :loading="treeLoading"
          animated
        >
          <el-tree
            :data="treeData"
            show-checkbox
            node-key="id"
            ref="treeRef"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </el-skeleton>
      </div>
    </div>

    <div class="content__footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, toRef, ref, PropType } from "vue";
import {
  searchRoleMenu,
  addrole,
  updaterole,
  postDictList
} from "/@/api/roles";
import { getMenuList } from "/@/api/menu";
// import { getMenuList } from "/@/api/mock";
import NotifMessage from "/@/utils/message/notification";

import { roleTypeEnum, ModeType, RoleInfoType } from "../types";

export default defineComponent({
  name: "roleSet",
  props: {
    mode: {
      type: String as PropType<ModeType>,
      require: true,
      default: "add"
    },
    // roleId: {
    //   type: Number,
    //   require: false,
    //   default: null
    // },
    roleInfo: {
      type: Object as PropType<RoleInfoType>,
      require: false,
      default: null
    }
  },
  emits: ["emitClose"],
  setup(props, { emit }) {
    let formRef = ref<HTMLFormElement | null>(null) as any;
    let treeRef = ref<HTMLElement | null>(null) as any;
    let treeLoading = ref<boolean>(false);
    const defaultProps = {
      children: "children",
      label: "menuName"
    };

    // 内外部角色
    let innerRoleList = ref([]);

    const treeData = ref([]);
    const roleInfoProp = toRef(props, "roleInfo");
    let state = reactive({
      formData: {
        roleName: "",
        roleDesc: "",
        roleType: "1",
        roleMark: ""
      }
    });

    // 如果是编辑状态
    if (props.mode === "edit") {
      // const copyRoleInfo = cloneDeep(roleInfoProp.value);
      const copyRoleInfo = roleInfoProp.value;
      state.formData = copyRoleInfo;
    }
    const formRules = ref({
      roleName: [
        { required: true, message: "请输入角色名称", trigger: "blur" }
      ],
      roleDesc: [
        { required: true, message: "请输入角色描述", trigger: "blur" }
      ],
      roleMark: [{ required: true, message: "请选择角色区分", trigger: "blur" }]
    });

    const onGetMenuList = async () => {
      try {
        treeLoading.value = true;
        const { code, data } = await getMenuList({});
        if (code === 200) {
          // data.forEach(item => {
          //   item.children.forEach(i => {
          //     i.resourceList.forEach(j => {
          //       j.menuName = j.resourceName;
          //       j.parentId = Number(j.resourceValue);
          //       j.id = `${item.id}${i.id}-${j.id}`;
          //     });
          //     i.children = i.resourceList;
          //   });
          // });
          // filterInitData(data);
          treeData.value = data;
          // nextTick(() => {
          if (props.mode === "edit") {
            getCurrentMenu();
          }
          // });
        }
      } catch (err) {
        console.log(err);
      } finally {
        treeLoading.value = false;
      }
    };

    // 过滤后端传来的动态路由重新生成规范路由
    // function childrenRouter(children: Array<string>) {
    //   if (!children || !children.length) return;
    //   children.forEach((k: any) => {
    //     k.component = modulesRoutes[`/src/views${k.path}/index.vue`];
    //     if (k.children?.length) {
    //       childrenRouter(k.children);
    //     }
    //   });
    // }

    // 初始化树结构
    // function filterInitData(data: Array<any>) {
    //   if (!data || !data.length) return;
    //   data.forEach((item: any) => {
    //     // item.children.forEach(i => {
    //     item.resourceList &&
    //       item.resourceList.forEach(j => {
    //         j.menuName = j.resourceName;
    //         j.parentId = Number(j.resourceValue);
    //         j.id = `${item.id}-${j.id}`;
    //       });
    //     if (item.resourceList) {
    //       item.children = item.resourceList;
    //     }
    //     // });
    //     if (item.children?.length) {
    //       filterInitData(item.children);
    //     }
    //   });
    // }

    // 根据后端返回的数据，将获取到的数据赋值 key ID，进行数据回显
    // function initGetMenu(data: Array<any>, result: Array<any>) {
    //   if (!data || !data.length) return;
    //   data.forEach(item => {
    //     if (item.resourceListitem.resourceList && item.resourceList.length) {
    //       item.resourceList.forEach(i => {
    //         result.push(`${item.menuId}-${i.id}`);
    //       });
    //     }
    //     if (item.secMenuList.length) {
    //       initGetMenu(item.secMenuList, result);
    //     }
    //   });
    // }

    // 根据角色id查询对应的菜单及权限
    const getCurrentMenu = async () => {
      try {
        const { code, data } = await searchRoleMenu({
          roleId: roleInfoProp.value.id
        });
        if (code === 200) {
          // initGetMenu(data, newResult);
          // data.forEach(item => {
          //   item.secMenuList.forEach(i => {
          //     i.resourceList.forEach(j => {
          //       newResult.push(`${i.menuId}-${j.id}`);
          //     });
          //   });
          // });
          // console.log(newResult, "newResult");

          var newArr = [];

          data.forEach(item => {
            checked(item, treeData.value, newArr);
          });
          // console.log(data, newArr, "初始化数据");
          // treeRef.value.checkedKeys = newArr;

          treeRef.value.setCheckedKeys(newArr);
        }
      } catch (error) {
        console.log(error);
      }
    };

    function checked(id, data, newArr) {
      data.forEach(item => {
        if (item.id == id) {
          if (item.children.length == 0) {
            newArr.push(item.id);
          }
        } else {
          if (item.children.length != 0) {
            checked(id, item.children, newArr);
          }
        }
      });
    }

    // function getChild(data, res = [], parentId) {
    //   for (const i of data) {
    //     if (i.parentId === parentId) {
    //       const newItem = { ...i, children: [] };
    //       res.push(newItem);
    //       getChild(data, newItem.children, i.id);
    //     }
    //   }
    // }

    // 获取所有的已选或者半选的节点
    function getCheckedNodes() {
      const newData = treeRef.value
        .getCheckedKeys()
        .concat(treeRef.value.getHalfCheckedKeys());
      return newData;
      // const filterData = [];
      // newData.forEach(item => {
      //   filterData.push({
      //     id: item.id,
      //     menuName: item.menuName,
      //     parentId: item.parentId
      //   });
      // });

      // const result = [];
      // getChild(filterData, result, 1);
      // result.forEach(item => {
      //   item.menuId = item.id;
      //   item.secMenuList = item.children;
      //   delete item.id;
      //   delete item.menuName;
      //   delete item.children;
      //   delete item.parentId;
      //   item.secMenuList.forEach(i => {
      //     i.menuId = i.id;
      //     i.resourceList = i.children;
      //     delete i.id;
      //     delete i.menuName;
      //     delete i.children;
      //     delete i.parentId;
      //     i.resourceList.forEach(j => {
      //       j.id = Number(j.id.match(/-(\S*)/)[1]);
      //       delete j.menuName;
      //       delete j.children;
      //       delete j.parentId;
      //     });
      //   });
      // });
      // return result;
    }

    // 确认授权
    // const onGiveRole = async () => {
    //   const result = getCheckedNodes();
    //   const params = {
    //     roleId: props.roleId,
    //     roleMenuList: result
    //   };
    //   try {
    //     const { code, message } = await roleMenu(params);
    //     if (code === 200) {
    //       successMessage(message);
    //     } else {
    //       warnMessage(message);
    //     }
    //   } catch (err) {
    //     console.log(err);
    //   } finally {
    //     // state.dialogRoleFormVisible = false;
    //   }
    // };

    const onAddRole = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        const res = getCheckedNodes();
        const params = {
          role: state.formData,
          menus: res
        };
        const { code, message } = await addrole(params);
        if (code === 200) {
          NotifMessage.success("添加成功");
          handleCancel();
        } else {
          NotifMessage.error(message);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const onUpdateRole = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        const res = getCheckedNodes();
        const params = {
          role: state.formData,
          menus: res
        };
        const { code, message } = await updaterole(params);
        if (code === 200) {
          NotifMessage.success("添加成功");
          handleCancel();
        } else {
          NotifMessage.error(message);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const handleCancel = () => {
      emit("emitClose");
    };
    const handleSubmit = () => {
      if (props.mode === "edit") {
        onUpdateRole();
      } else {
        onAddRole();
      }
    };

    // 变更类型
    const initRoleTypeList = async () => {
      try {
        const params = {
          dicType: "role_mark"
        };
        const { code, data } = await postDictList(params);
        innerRoleList.value = data;
        console.log(code, data);
      } catch (err) {
        console.log(err);
      }
    };

    onGetMenuList();
    initRoleTypeList();

    return {
      getCheckedNodes,
      props,
      formRef,
      treeRef,
      treeLoading,
      defaultProps,
      treeData,
      ...toRefs(state),
      formRules,
      roleTypeEnum,
      innerRoleList,
      handleCancel,
      handleSubmit
    };
  }
});
</script>

<style lang="scss" scoped>
.roleSet {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  .content__body {
    width: 100%;
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    &__tree {
      padding: 10px;
      p {
        font-size: 14px;
        color: #606266;
        line-height: 32px;
      }
    }
  }
  .content__footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 60px;
    border-top: 1px solid rgba(0, 21, 41, 0.15);
    padding: 15px;
  }
}
</style>
